package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.tencent.request.TencentSendNoTeRequest;
import com.common.tencent.template.TencentNoteTemPlate;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.domain.vo.AgencyInventoryVo;
import com.ruoyi.system.domain.vo.BdmCloudInventoryItemVo;
import com.ruoyi.system.domain.vo.BdmOrderItemVo;
import com.ruoyi.system.domain.vo.applet.AppletCloudInventoryVo;
import com.ruoyi.system.domain.vo.applet.CommodityDetailsVo;
import com.ruoyi.system.enums.*;
import com.ruoyi.system.mapper.BdmCloudInventoryMapper;
import com.ruoyi.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 云库存Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-24
 */
@Slf4j
@Service
public class BdmCloudInventoryServiceImpl extends ServiceImpl<BdmCloudInventoryMapper, BdmCloudInventory> implements IBdmCloudInventoryService {
    @Autowired
    private BdmCloudInventoryMapper bdmCloudInventoryMapper;

    //云库存明细
    @Autowired
    private IBdmCloudInventoryItemService bdmCloudInventoryItemService;

    //用户
    @Autowired
    private IBdmUserService bdmUserService;

    //获取事务
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    //用户等级
    @Autowired
    private IBdmMemberRuleService bdmMemberRuleService;

    //订单项
    @Autowired
    private IBdmOrderItemService bdmOrderItemService;

    //订单
    @Autowired
    private IBdmOrderService bdmOrderService;
    //商品
    @Autowired
    private IBdmGoodService bdmGoodService;
    @Autowired
    //用户 余额 积分 佣金 变动
    private IBdmBalanceChangeService bdmBalanceChangeService;

    @Autowired
    private TencentNoteTemPlate tencentNoteTemPlate;

    @Autowired
    private IBdmPayService bdmPayService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询云库存
     *
     * @param id 云库存主键
     * @return 云库存
     */
    @Override
    public BdmCloudInventory selectBdmCloudInventoryById(Long id) {
        return bdmCloudInventoryMapper.selectBdmCloudInventoryById(id);
    }

    /**
     * 查询云库存列表
     *
     * @param bdmCloudInventory 云库存
     * @return 云库存
     */
    @Override
    public List<BdmCloudInventory> selectBdmCloudInventoryList(BdmCloudInventory bdmCloudInventory) {
        return bdmCloudInventoryMapper.selectBdmCloudInventoryList(bdmCloudInventory);
    }

    /**
     * 新增云库存
     *
     * @param bdmCloudInventory 云库存
     * @return 结果
     */
    @Override
    public int insertBdmCloudInventory(BdmCloudInventory bdmCloudInventory) {
        bdmCloudInventory.setCreateTime(DateUtils.getNowDate());
        return bdmCloudInventoryMapper.insertBdmCloudInventory(bdmCloudInventory);
    }

    /**
     * 修改云库存
     *
     * @param bdmCloudInventory 云库存
     * @return 结果
     */
    @Override
    public int updateBdmCloudInventory(BdmCloudInventory bdmCloudInventory) {
        bdmCloudInventory.setUpdateTime(DateUtils.getNowDate());
        return bdmCloudInventoryMapper.updateBdmCloudInventory(bdmCloudInventory);
    }

    /**
     * 批量删除云库存
     *
     * @param ids 需要删除的云库存主键
     * @return 结果
     */
    @Override
    public int deleteBdmCloudInventoryByIds(Long[] ids) {
        return bdmCloudInventoryMapper.deleteBdmCloudInventoryByIds(ids);
    }

    /**
     * 删除云库存信息
     *
     * @param id 云库存主键
     * @return 结果
     */
    @Override
    public int deleteBdmCloudInventoryById(Long id) {
        return bdmCloudInventoryMapper.deleteBdmCloudInventoryById(id);
    }


    /**
     * 增减库存   type   BdmCloudInventoryEnum.SUB.getType() 减库存    BdmCloudInventoryEnum.ADD.getType()  回库存
     */
    @Override
    public void addOrRollBackStock(List<BdmCloudInventoryItem> bdmCloudInventoryItems, Long type) {
        int cardinalNumber = 1;

        if (ObjectUtils.isNotEmpty(type) && type.equals(BdmGoodEnum.ADD.getType())) {
            cardinalNumber = -1;
        }
        //批量回库存
        //获取sqlSession
        SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        //获取 库存mapper
        BdmCloudInventoryMapper bdmCloudInventoryMapper = sqlSession.getMapper(BdmCloudInventoryMapper.class);
        try {
            //回库存
            for (BdmCloudInventoryItem bdmCloudInventoryItem : bdmCloudInventoryItems) {


                int i = bdmCloudInventoryMapper.reduceInventory(bdmCloudInventoryItem.getUserId(), bdmCloudInventoryItem.getGoodId(), bdmCloudInventoryItem.getNum() * cardinalNumber);//用户id  商品id   本次购买数量
                if (i == 0) {
                    throw new RuntimeException("操作失败请联系管理员");
                }
            }
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e.getMessage());
        } finally {
            sqlSession.close();
        }
    }


    //根据订单项添加云库存
    @Override
    @Transactional
    public void addBdmCloudInventory(List<BdmOrderItem> bdmOrderItems, BdmUser bdmUser) {
        // LoginUser loginUser = SecurityUtils.getLoginUser();
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(bdmOrderService.selectBdmOrderById(bdmOrderItems.get(0).getOrderId()).getUserId());
        //会员等级
        BdmMemberRule bdmMemberRule = bdmMemberRuleService.lambdaQuery().eq(BdmMemberRule::getSysUserid, bdmUser.getSysUserid()).one();
        Date nowDate = DateUtils.getNowDate();


        //商品id
        List<Long> orderItemIds = bdmOrderItems.stream().map(BdmOrderItem::getId).collect(Collectors.toList());

        //转map
        Map<Long, BdmOrderItem> map = bdmOrderItems.stream().collect(Collectors.toMap(i -> Long.parseLong(i.getSupplierGoodId()), item -> item));


        //如果没有上级 或者会员等级不是代理 就直接返回
        if (ObjectUtils.isEmpty(bdmUser.getParentId())) {
            return;
        }

        //去订单项查出云库存商品的 数量和商品详细信息
        List<BdmGoodDto> bdmGoodDtos = bdmOrderItemService.selectGoodItemList(orderItemIds);

        for (BdmGoodDto bdmGoodDto : bdmGoodDtos) {
            BdmOrderItem bdmOrderItem = null;
            if (map.containsKey(bdmGoodDto.getId())) {
                bdmOrderItem = map.get(bdmGoodDto.getId());
            }

            //如果是大礼包默认开通云库存
            if (bdmGoodDto.getClassOneName().equals(BdmGoodEnum.GIFT_PACKS.getDescription())) {
                //查询用户之前有没有这个商品 如果有就是进货修改库存
                BdmCloudInventory bdmCloudInventoryItem = this.lambdaQuery()
                        .eq(BdmCloudInventory::getUserId, bdmUser.getSysUserid())//用户id
                        .eq(BdmCloudInventory::getGoodId, bdmGoodDto.getId())//相同商品
                        .one();

                //填充 云库存对象
                BdmCloudInventory bdmCloudInventory = new BdmCloudInventory();
                if (ObjectUtils.isNotEmpty(bdmCloudInventoryItem)) {
                    if (ObjectUtils.isEmpty(bdmCloudInventoryItem.getGoodInventory()) || "null".equals(bdmCloudInventoryItem.getGoodInventory())) {
                        bdmCloudInventoryItem.setGoodInventory("0");
                    }
                    BeanUtil.copyProperties(bdmCloudInventoryItem, bdmCloudInventory);
                    bdmCloudInventory.setUpdateBy(loginUser.getUserId().toString());
                    bdmCloudInventory.setUpdateTime(DateUtils.getNowDate());
                } else {
                    bdmCloudInventory.setCreateTime(nowDate);
                    bdmCloudInventory.setCreateBy(loginUser.getUserId().toString());
                    bdmCloudInventory.setUpdateBy(loginUser.getUserId().toString());
                    bdmCloudInventory.setUpdateTime(nowDate);
                }

                bdmCloudInventory.setGoodId(bdmGoodDto.getId());//商品id
                bdmCloudInventory.setUserId(bdmUser.getSysUserid());//用户id

                if (ObjectUtils.isNotEmpty(bdmGoodDto.getProductLevel()) && bdmGoodDto.getProductLevel() > BdmMemberRuleEnum.SVIP.getLevel()) {   //如果商品有等级 进货价就是售价
                    bdmCloudInventory.setStockPrice(bdmGoodDto.getRetailPrice());//进货价
                } else { //根据当前用户等级来
                    //保底价格
                    bdmCloudInventory.setStockPrice(bdmGoodDto.getRetailPrice());//进货价

                    if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberLevel()) && bdmMemberRule.getMemberLevel().equals(BdmMemberRuleEnum.VIP.getLevel())) { //vip
                        bdmCloudInventory.setStockPrice(bdmGoodDto.getVipPrice());//进货价
                    }
                    if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberLevel()) && bdmMemberRule.getMemberLevel().equals(BdmMemberRuleEnum.SVIP.getLevel())) {//svip
                        bdmCloudInventory.setStockPrice(bdmGoodDto.getSvipPrice());//进货价
                    }
                    if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.SHOPKEEPER.getLevel())) {//共享
                        bdmCloudInventory.setStockPrice(bdmGoodDto.getSharePrice());//进货价
                    }
                    if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.LAIN_CHANG.getLevel())) {//联创
                        bdmCloudInventory.setStockPrice(bdmGoodDto.getJoinPrice());//进货价
                    }
                    if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.OPERATION.getLevel())) {//运营
                        bdmCloudInventory.setStockPrice(bdmGoodDto.getOperationsPrice());//进货价
                    }
                    if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.BOSS.getLevel())) {//总裁
                        bdmCloudInventory.setStockPrice(bdmGoodDto.getPresidentPrice());//进货价
                    }
                }
                bdmCloudInventory.setRetailPrice(bdmGoodDto.getRetailPrice());//售价
                bdmCloudInventory.setProfit(bdmCloudInventory.getRetailPrice().subtract(bdmCloudInventory.getStockPrice()));//利润
                bdmCloudInventory.setGoodInventory(String.valueOf(ObjectUtils.isEmpty(bdmCloudInventory.getGoodInventory()) ? bdmGoodDto.getGoodInventory() : Long.parseLong(bdmCloudInventory.getGoodInventory()) + bdmGoodDto.getGoodInventory()));//库存
                bdmCloudInventory.setGoodImg(bdmGoodDto.getGoodImg());//商品主图
                bdmCloudInventory.setGoodName(bdmGoodDto.getGoodName());//商品名称
                bdmCloudInventory.setGoodSpecs(bdmGoodDto.getGoodSpecs());//商品规格
                //添加或者修改云库存
                this.saveOrUpdate(bdmCloudInventory);

                //-----------------------单品 找上级买----------------------
            } else {
                //2025-70-30  徐小波新增；只有单品才会走云库存
                if (!bdmGoodDto.getClassOneName().equals(BdmGoodEnum.ONE_GRADE.getDescription())) {
                    continue;
                }
                //TODO 查询等级比自己高的上级
                Long parentId = getParent(bdmUser, bdmMemberRule);
                BdmUser parentBdmUser = null;
                SysUser sysUser = null;
                if (!parentId.equals(0L)) {
                    parentBdmUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, parentId).one();
                    sysUser = sysUserService.selectUserById(parentBdmUser.getSysUserid());
                }
                //TODO 增加上级的 收益
                if (ObjectUtils.isNotEmpty(parentBdmUser) && ObjectUtils.isNotEmpty(sysUser) && ObjectUtils.isNotEmpty(bdmOrderItem)) {
                    BigDecimal earnings = parentBdmUser.getEarnings();
                    BigDecimal multiply = bdmOrderItem.getGoodPrice();
                    BigDecimal sum = earnings.add(multiply);
                    parentBdmUser.setEarnings(sum);
                    bdmUserService.updateById(parentBdmUser);
                    //记录佣金变动
                    BdmBalanceChange bdmBalanceChange = new BdmBalanceChange();
                    bdmBalanceChange.setUserId(sysUser.getUserId());
                    bdmBalanceChange.setUserPhone(sysUser.getPhonenumber());
                    bdmBalanceChange.setNickName(sysUser.getNickName());
                    bdmBalanceChange.setRelevantDocumentId(bdmOrderItem.getOrderId());
                    bdmBalanceChange.setVariation(multiply.toString());
                    bdmBalanceChange.setVariationBefore(earnings.toString());
                    bdmBalanceChange.setVariationAfter(sum.toString());
                    bdmBalanceChange.setVariationType(Long.parseLong(BdmBalanceChangeEnum.BROKERAGE.getType()));
                    bdmBalanceChange.setAddOrSubtract(Long.parseLong(BdmBalanceChangeEnum.ADD.getType()));
                    bdmBalanceChange.setBusinessType(BdmBalanceChangeEnum.LOWER_LEVEL_PURCHASES_OF_CLOUD_INVENTORY_ITEMS.getDescription());
                    bdmBalanceChange.setCreateTime(nowDate);
                    bdmBalanceChangeService.insertBdmBalanceChange(bdmBalanceChange);
                }

                //查询上级云库存
                BdmCloudInventory bdmCloudInventory = this.lambdaQuery()
                        .eq(BdmCloudInventory::getGoodId, bdmGoodDto.getId())
                        .eq(BdmCloudInventory::getUserId, parentId)
                        .ge(BdmCloudInventory::getGoodInventory, bdmGoodDto.getNumber())
                        .one();
                //云库存明细对象
                BdmCloudInventoryItem item = new BdmCloudInventoryItem();
                item.setCloudInventoryId(ObjectUtils.isEmpty(bdmCloudInventory) ? null : bdmCloudInventory.getId());//云库存id
                item.setGoodId(bdmGoodDto.getId()); //商品id
                item.setGoodName(bdmGoodDto.getGoodName());//商品名称
                item.setGoodImg(bdmGoodDto.getGoodImg());//商品图片
                item.setNum(Long.valueOf(bdmGoodDto.getNumber()));//商品数量
                item.setUserId(bdmUser.getSysUserid());// 用户id
                item.setCorrelationUserId(parentId);//上下级id
                item.setRelevantDocumentId(bdmOrderItems.get(0).getOrderId());// 相关单据id
                item.setStockType(BdmCloudInventoryEnum.IN_STOCK.getType());//进货状态 进货中
                item.setMoney(bdmOrderItem.getGoodPrice());//本次金额
                item.setNumType(BdmCloudInventoryEnum.NUM_TYPE_ADD.getType());//数量类型 增加
                item.setVariationType(BdmCloudInventoryEnum.GET_GOODS.getDescription());//找上级拿货

                //上级有货就把时间改为现在  没货改为24小时
                item.setStockTime(!ObjectUtils.isEmpty(bdmCloudInventory) || parentId.equals(0L) ? nowDate : new Date(System.currentTimeMillis() + 1000 * 60 * 60 * BdmCloudInventoryEnum.STOCK_HOUR.getType()));//进货时间
                item.setCreateTime(nowDate);//创建时间
                item.setCreateBy(bdmUser.getSysUserid().toString());//创建用户
                item.setUpdateTime(nowDate);//修改时间
                item.setUpdateBy(bdmUser.getSysUserid().toString());//修改用户
                bdmUser.setParentId(parentId);
                //TODO  发送短信给上级提醒进货
                sendNote(bdmUser);
                log.debug("发送短信给上级提醒进货");
                bdmCloudInventoryItemService.save(item);
                //添加修改云库存明细
                this.addBdmCloudInventoryItem(item, bdmUser);
            }


        }
    }

    /**
     * 递归找上级
     */
    public Long getParent(BdmUser bdmUser, BdmMemberRule bdmMemberRule) {
        BdmMemberRule parentRule = bdmMemberRuleService.lambdaQuery().eq(BdmMemberRule::getSysUserid, bdmUser.getParentId()).one();
        if (parentRule == null) {
            return 0l;
        }
        if (ObjectUtils.isEmpty(parentRule) && ObjectUtils.isEmpty(parentRule.getMemberLevel()) && ObjectUtils.isEmpty(parentRule.getMemberAgencyLevel())) {
            return 0L;
        }

        if (ObjectUtils.isEmpty(bdmMemberRule)) {
            return parentRule.getSysUserid();
        }

        long parentLevel = Math.max(parentRule.getMemberLevel() == null ? 0 : parentRule.getMemberLevel(),
                parentRule.getMemberAgencyLevel() == null ? 0 : parentRule.getMemberAgencyLevel());
        long Level = Math.max(ObjectUtils.isEmpty(bdmMemberRule.getMemberLevel()) ? 0L : bdmMemberRule.getMemberLevel(), ObjectUtils.isEmpty(bdmMemberRule.getMemberAgencyLevel()) ? 0L : bdmMemberRule.getMemberAgencyLevel());

        if (parentLevel > Level) {
            return parentRule.getSysUserid();
        }
        BdmUser one = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, parentRule.getSysUserid()).one();
        if (ObjectUtils.isEmpty(one)) {
            return 0L;
        }
        return getParent(one, bdmMemberRule);
    }


    /**
     * 根据 商品 和用户 信息  返回 云库存明细信息
     */
    @Override
    @Transactional
    public void addBdmCloudInventoryItem(BdmCloudInventoryItem bdmCloudInventoryItemDto, BdmUser bdmUser) {
        // 进货未到时间的返回
        if (ObjectUtils.isEmpty(bdmCloudInventoryItemDto) ||
                ObjectUtils.isEmpty(bdmCloudInventoryItemDto.getStockType()) ||
                bdmCloudInventoryItemDto.getStockType().equals(BdmCloudInventoryEnum.ACCOMPLISH.getType()) ||
                bdmCloudInventoryItemDto.getStockTime().compareTo(new Date()) > 0) {
            return;
        }

        BdmCloudInventory bdmCloudInventory = bdmCloudInventoryMapper.selectBdmCloudInventoryById(bdmCloudInventoryItemDto.getCloudInventoryId());


        //云库存明细集合
        List<BdmCloudInventoryItem> bdmCloudInventoryItems = new ArrayList<>();
        bdmCloudInventoryItems.add(bdmCloudInventoryItemDto);

        Date nowDate = DateUtils.getNowDate();
        //查询用户有没有上级  如果没有 则走商城购买

        //如果有上级则走上级购买
        Long parentId = bdmCloudInventoryItemDto.getCorrelationUserId();
        BdmCloudInventory itemBdmCloudInventory = this.lambdaQuery()
                .eq(BdmCloudInventory::getUserId, parentId)//云库存表存在 上级id
                .eq(BdmCloudInventory::getGoodId, bdmCloudInventoryItemDto.getGoodId())//相同商品
                .ge(BdmCloudInventory::getGoodInventory, bdmCloudInventoryItemDto.getNum()) //库存数量足够
                .one();
        //如果上级有货
        if (ObjectUtils.isNotEmpty(itemBdmCloudInventory)) {
            bdmCloudInventoryItemDto.setStockType(BdmCloudInventoryEnum.ACCOMPLISH.getType());//进货状态 已完成
            //扣减上级 云库存
            BdmCloudInventoryItem itemSub = BeanUtil.copyProperties(bdmCloudInventoryItemDto, BdmCloudInventoryItem.class);
            itemSub.setId(null);
            itemSub.setNumType(BdmCloudInventoryEnum.NUM_TYPE_SUB.getType());//数量类型  减
            itemSub.setVariationType(BdmCloudInventoryEnum.STOCK.getDescription());// 变动类型 被下级进货
            itemSub.setCloudInventoryId(itemBdmCloudInventory.getId());
            itemSub.setUserId(parentId);//用户id
            itemSub.setCorrelationUserId(bdmUser.getSysUserid());//  下级id
            itemSub.setStockType(BdmCloudInventoryEnum.ACCOMPLISH.getType());//进货状态 已完成
            itemSub.setMoney(new BigDecimal("0"));//本次金额
            itemSub.setCreateTime(nowDate);//创建时间
            itemSub.setCreateBy(bdmUser.getSysUserid().toString());//创建用户
            itemSub.setUpdateTime(nowDate);//修改时间
            itemSub.setUpdateBy(bdmUser.getSysUserid().toString());//修改用户
            bdmCloudInventoryItems.add(itemSub);

            bdmCloudInventoryItemService.saveOrUpdateBatch(bdmCloudInventoryItems);
            // 根据明细 处理库存
            this.addOrRollBackByCloudInventoryItem(bdmCloudInventoryItems);
            return;
        }
        //如果上级没货 则提醒上级进货
        BdmCloudInventoryItem itemSub = new BdmCloudInventoryItem();
        BeanUtil.copyProperties(bdmCloudInventoryItemDto, itemSub);

        //走到这说明上级也没货  找更上级
        //查询 更上级  用户信息
        BdmUser itemBdmUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, parentId).one();

        // 此处徐小波增加逻辑，找的上级必须是代理等级比BdmUser高的；
        Long parentId1 = 0l;
        if (!ObjectUtils.isEmpty(itemBdmUser)) {
            BdmMemberRule bdmMemberRule = bdmMemberRuleService.lambdaQuery().eq(BdmMemberRule::getSysUserid, parentId).one();
            parentId1 = getParent(itemBdmUser, bdmMemberRule);
            //  itemBdmUser.setParentId(parentId1);
        }

        if (ObjectUtils.isEmpty(itemBdmUser) || ObjectUtils.isEmpty(itemBdmUser.getParentId()) || (parentId1.equals(0l))) {//如果更上级不存在 则找平台购买
            //云库存明细对象
            BdmCloudInventoryItem bdmCloudInventoryItem = BeanUtil.copyProperties(bdmCloudInventoryItemDto, BdmCloudInventoryItem.class);
            bdmCloudInventoryItem.setNumType(BdmCloudInventoryEnum.NUM_TYPE_ADD.getType());//数量类型   加
            bdmCloudInventoryItem.setVariationType(BdmCloudInventoryEnum.MALL_PURCHASE.getDescription());// 变动类型 商城购买
            bdmCloudInventoryItem.setUserId(bdmUser.getSysUserid());//用户id
            bdmCloudInventoryItem.setCorrelationUserId(0L);//补货上下级  平台
            bdmCloudInventoryItem.setStockType(BdmCloudInventoryEnum.ACCOMPLISH.getType());//进货状态 已完成
            bdmCloudInventoryItem.setMoney(bdmCloudInventoryItemDto.getMoney());//本次金额
            bdmCloudInventoryItem.setStockTime(DateUtils.getNowDate());//进货时间
            bdmCloudInventoryItem.setCreateTime(nowDate);//创建时间
            bdmCloudInventoryItem.setCreateBy(bdmUser.getSysUserid().toString());//创建用户
            bdmCloudInventoryItem.setUpdateTime(nowDate);//修改时间
            bdmCloudInventoryItem.setUpdateBy(bdmUser.getSysUserid().toString());//修改用户
            bdmCloudInventoryItems.add(bdmCloudInventoryItem);
            //保存云库存明细
            bdmCloudInventoryItemService.saveOrUpdateBatch(bdmCloudInventoryItems);
            // 根据明细 处理库存
            this.addOrRollBackByCloudInventoryItem(bdmCloudInventoryItems);
            //TODO 减少上级收益
            BdmUser sysUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, parentId).one();
            if (ObjectUtils.isNotEmpty(sysUser)) {
                BigDecimal multiply = bdmCloudInventoryItemDto.getMoney();

                //插入余额收益积分变动表
                BdmBalanceChange bdmBalanceChange = BdmBalanceChange.getBdmBalanceChange(
                        sysUser.getSysUserid(),
                        ObjectUtils.isEmpty(bdmCloudInventory) ? null : bdmCloudInventory.getId().toString(),
                        multiply.toString(),
                        sysUser.getEarnings().toString(),
                        sysUser.getEarnings().subtract(multiply).toString(),
                        Long.parseLong(BdmBalanceChangeEnum.BROKERAGE.getType()),
                        Long.parseLong(BdmBalanceChangeEnum.SUBTRACT.getType()),
                        BdmBalanceChangeEnum.NO_REPLENISHMENT.getDescription()
                );
                sysUser.setEarnings(sysUser.getEarnings().subtract(multiply));
                bdmBalanceChangeService.save(bdmBalanceChange);
                bdmUserService.updateById(sysUser);
            }
            return;
        }

        // 设置parentiD ,不是直属parentId；而是代理等级高的parentId
        itemBdmUser.setParentId(parentId1);
        //查看更上级有没有货有货就直接买没货就24小时进货 TODO  ------------------------------------
        BdmCloudInventory one = this.lambdaQuery()
                .eq(BdmCloudInventory::getUserId, itemBdmUser.getParentId())
                .eq(BdmCloudInventory::getGoodId, bdmCloudInventoryItemDto.getGoodId())
                .ge(BdmCloudInventory::getGoodInventory, bdmCloudInventoryItemDto.getNum()).one();


        //TODO 减少上级收益 增加更上级收益
        BdmUser sysUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, parentId).one();

        BdmUser sysUserP = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, itemBdmUser.getParentId()).one();

        BigDecimal multiply = bdmCloudInventoryItemDto.getMoney();

        //插入余额收益积分变动表
        BdmBalanceChange bdmBalanceChange = BdmBalanceChange.getBdmBalanceChange(
                sysUser.getSysUserid(),
                ObjectUtils.isEmpty(bdmCloudInventory) ? null : bdmCloudInventory.getId().toString(),
                multiply.toString(),
                sysUser.getEarnings().toString(),
                sysUser.getEarnings().subtract(multiply).toString(),
                Long.parseLong(BdmBalanceChangeEnum.BROKERAGE.getType()),
                Long.parseLong(BdmBalanceChangeEnum.SUBTRACT.getType()),
                BdmBalanceChangeEnum.NO_REPLENISHMENT.getDescription()
        );
        BdmBalanceChange bdmBalanceChange1 = BdmBalanceChange.getBdmBalanceChange(
                sysUserP.getSysUserid(),
                ObjectUtils.isEmpty(bdmCloudInventory) ? null : bdmCloudInventory.getId().toString(),
                multiply.toString(),
                sysUserP.getEarnings().toString(),
                sysUserP.getEarnings().add(multiply).toString(),
                Long.parseLong(BdmBalanceChangeEnum.BROKERAGE.getType()),
                Long.parseLong(BdmBalanceChangeEnum.ADD.getType()),
                BdmBalanceChangeEnum.LOWER_LEVEL_PURCHASES_OF_CLOUD_INVENTORY_ITEMS.getDescription()
        );
        sysUser.setEarnings(sysUser.getEarnings().subtract(multiply));
        sysUserP.setEarnings(sysUserP.getEarnings().add(multiply));

        bdmBalanceChangeService.save(bdmBalanceChange);
        bdmBalanceChangeService.save(bdmBalanceChange1);
        bdmUserService.updateById(sysUser);
        bdmUserService.updateById(sysUserP);

        itemSub.setCorrelationUserId(itemBdmUser.getParentId());//查找更上级
        itemSub.setNumType(BdmCloudInventoryEnum.NUM_TYPE_ADD.getType());//数量类型  增加
        itemSub.setVariationType(BdmCloudInventoryEnum.GET_GOODS.getDescription());// 变动类型 找上级拿货
        itemSub.setStockType(BdmCloudInventoryEnum.IN_STOCK.getType());//进货状态 进货中
        itemSub.setMoney(bdmCloudInventoryItemDto.getMoney());//本次金额
        itemSub.setStockTime(ObjectUtils.isEmpty(one) ? new Date(System.currentTimeMillis() + 1000 * 60 * 60 * BdmCloudInventoryEnum.STOCK_HOUR.getType()) : nowDate);//进货时间
        itemSub.setCreateTime(nowDate);//创建时间
        itemSub.setCreateBy(bdmUser.getSysUserid().toString());//创建用户
        itemSub.setUpdateTime(nowDate);//修改时间
        itemSub.setUpdateBy(bdmUser.getSysUserid().toString());//修改用户
        bdmCloudInventoryItems.add(itemSub);
        bdmCloudInventoryItemService.saveOrUpdateBatch(bdmCloudInventoryItems);

        //上级有货直接扣减上级云库存
        if (ObjectUtils.isNotEmpty(one)) {
            this.addBdmCloudInventoryItem(itemSub, bdmUser);
        }

        // 根据明细 处理库存
        this.addOrRollBackByCloudInventoryItem(bdmCloudInventoryItems);
        //TODO  发送短信给上级提醒进货
        sendNote(bdmUser);
        log.debug("发送短信给上级提醒进货");
    }

    /**
     * 查询代理库存列表
     */
    @Override
    public List<AgencyInventoryVo> listAgencyInventory(BdmCloudInventoryDto bdmCloudInventoryDto) {
        return bdmCloudInventoryMapper.listAgencyInventory(bdmCloudInventoryDto);
    }


    /**
     * 修改云库存 后台编辑库存
     */
    @Override
    @Transactional
    public boolean modifiedInventory(BdmCloudInventoryEditDto bdmCloudInventoryEditDto) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Date nowDate = DateUtils.getNowDate();
        List<BdmCloudInventoryItem> bdmCloudInventoryItems = new ArrayList<>();
        //会员等级
        BdmMemberRule bdmMemberRule = bdmMemberRuleService.lambdaQuery().eq(BdmMemberRule::getSysUserid, bdmCloudInventoryEditDto.getUserId()).one();
        // 记录云库存明细  增加云库存 从商品库存扣
        if (bdmCloudInventoryEditDto.getInventoryType().equals(BdmCloudInventoryEnum.NUM_TYPE_ADD.getType())) {
            BdmGood bdmGood = bdmGoodService.lambdaQuery().eq(BdmGood::getId, bdmCloudInventoryEditDto.getGoodId()).one();
            //商品库存
            Long goodInventory = Long.parseLong(bdmGood.getGoodInventory());
            //要增加的云库存
            Long cloudInventory = bdmCloudInventoryEditDto.getGoodInventory();
            if (cloudInventory.compareTo(goodInventory) > 0) {
                throw new RuntimeException("商品库存不足");
            }
            Long id = null;
            //查询有没有 这个云库存 没有就增加
            BdmCloudInventory bdmCloudInventory = this.lambdaQuery()
                    .eq(BdmCloudInventory::getUserId, bdmCloudInventoryEditDto.getUserId())
                    .eq(BdmCloudInventory::getGoodId, bdmCloudInventoryEditDto.getGoodId())
                    .one();
            if (ObjectUtils.isEmpty(bdmCloudInventory)) {//之前没有 需要新增
                BdmCloudInventory item = new BdmCloudInventory();
                item.setGoodId(bdmGood.getId()); //商品id
                item.setGoodName(bdmGood.getGoodName());//商品名称
                item.setGoodImg(bdmGood.getGoodImg());//商品主图
                item.setGoodInventory("0");//库存
                item.setGoodSpecs(bdmGood.getGoodSpecs());//商品规格
                item.setUserId(bdmCloudInventoryEditDto.getUserId());//用户id
                item.setRetailPrice(bdmGood.getRetailPrice());//建议零售价
                item.setCreateTime(nowDate);//创建时间
                item.setCreateBy(loginUser.getUserId().toString());//创建时间
                item.setUpdateTime(nowDate);//创建时间
                item.setUpdateBy(loginUser.getUserId().toString());//创建时间
                if (ObjectUtils.isNotEmpty(bdmGood.getProductLevel())) {   //如果商品有等级 进货价就是售价
                    item.setStockPrice(bdmGood.getRetailPrice());//进货价
                } else { //根据当前用户等级来
                    item.setStockPrice(bdmGood.getRetailPrice());//进货价
                    if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberLevel()) && bdmMemberRule.getMemberLevel().equals(BdmMemberRuleEnum.VIP.getLevel())) { //vip
                        item.setStockPrice(bdmGood.getVipPrice());//进货价
                    }
                    if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberLevel()) && bdmMemberRule.getMemberLevel().equals(BdmMemberRuleEnum.SVIP.getLevel())) {//svip
                        item.setStockPrice(bdmGood.getSvipPrice());//进货价
                    }
                    if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.SHOPKEEPER.getLevel())) {//共享
                        item.setStockPrice(bdmGood.getSharePrice());//进货价
                    }
                    if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.LAIN_CHANG.getLevel())) {//联创
                        item.setStockPrice(bdmGood.getJoinPrice());//进货价
                    }
                    if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.OPERATION.getLevel())) {//运营
                        item.setStockPrice(bdmGood.getOperationsPrice());//进货价
                    }
                    if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.BOSS.getLevel())) {//总裁
                        item.setStockPrice(bdmGood.getPresidentPrice());//进货价
                    }
                }
                item.setProfit(item.getRetailPrice().subtract(item.getStockPrice()));//利润
                this.save(item);
                id = item.getId();
            } else {
                id = bdmCloudInventory.getId();
            }
            //新增云库存明细表
            BdmCloudInventoryItem bdmCloudInventoryItem = new BdmCloudInventoryItem();
            bdmCloudInventoryItem.setCloudInventoryId(id);// 云库存id
            bdmCloudInventoryItem.setGoodId(bdmGood.getId());//商品id
            bdmCloudInventoryItem.setGoodName(bdmGood.getGoodName());//商品名称
            bdmCloudInventoryItem.setGoodImg(bdmGood.getGoodImg());//商品图片
            bdmCloudInventoryItem.setNum(bdmCloudInventoryEditDto.getGoodInventory());//购买数量
            bdmCloudInventoryItem.setNumType(BdmCloudInventoryEnum.NUM_TYPE_ADD.getType());//数量类型  加
            bdmCloudInventoryItem.setVariationType(BdmCloudInventoryEnum.SYSTEM_ADDITION.getDescription());// 变动类型 系统添加
            bdmCloudInventoryItem.setUserId(bdmCloudInventoryEditDto.getUserId());//用户id
            bdmCloudInventoryItem.setCorrelationUserId(0L);// 相关用户id
            bdmCloudInventoryItem.setStockType(BdmCloudInventoryEnum.ACCOMPLISH.getType());//进货状态 已完成
            bdmCloudInventoryItem.setMoney(new BigDecimal("0"));//本次金额
            bdmCloudInventoryItem.setStockTime(nowDate);// 进货时间
            bdmCloudInventoryItem.setCreateTime(nowDate);//创建时间
            bdmCloudInventoryItem.setCreateBy(loginUser.getUserId().toString());//创建用户
            bdmCloudInventoryItem.setUpdateTime(nowDate);//修改时间
            bdmCloudInventoryItem.setUpdateBy(loginUser.getUserId().toString());//修改用户
            bdmCloudInventoryItemService.save(bdmCloudInventoryItem);
            bdmCloudInventoryItems.add(bdmCloudInventoryItem);
            // 记录云库存明细  增减少云库存 增加商品库存
        } else if (bdmCloudInventoryEditDto.getInventoryType().equals(BdmCloudInventoryEnum.NUM_TYPE_SUB.getType())) {

            BdmCloudInventory bdmCloudInventory = this.lambdaQuery()
                    .eq(BdmCloudInventory::getUserId, bdmCloudInventoryEditDto.getUserId())
                    .eq(BdmCloudInventory::getGoodId, bdmCloudInventoryEditDto.getGoodId()).one();


            Long goodInventory = Long.parseLong(bdmCloudInventory.getGoodInventory());
            if (ObjectUtils.isEmpty(bdmCloudInventory) || bdmCloudInventoryEditDto.getGoodInventory().compareTo(goodInventory) > 0) {
                throw new RuntimeException("云库存数量不足");
            }
            //新增云库存明细表
            BdmCloudInventoryItem bdmCloudInventoryItem = new BdmCloudInventoryItem();
            bdmCloudInventoryItem.setCloudInventoryId(bdmCloudInventoryEditDto.getId());// 云库存id
            bdmCloudInventoryItem.setGoodId(bdmCloudInventory.getGoodId());//商品id
            bdmCloudInventoryItem.setGoodName(bdmCloudInventory.getGoodName());//商品名称
            bdmCloudInventoryItem.setGoodImg(bdmCloudInventory.getGoodImg());//商品图片
            bdmCloudInventoryItem.setNum(bdmCloudInventoryEditDto.getGoodInventory());//购买数量
            bdmCloudInventoryItem.setNumType(BdmCloudInventoryEnum.NUM_TYPE_SUB.getType());//数量类型  减
            bdmCloudInventoryItem.setVariationType(BdmCloudInventoryEnum.SYSTEM_REDUCTION.getDescription());// 变动类型 系统减少
            bdmCloudInventoryItem.setUserId(bdmCloudInventoryEditDto.getUserId());//用户id
            bdmCloudInventoryItem.setCorrelationUserId(0L);// 相关用户id
            bdmCloudInventoryItem.setStockType(BdmCloudInventoryEnum.ACCOMPLISH.getType());//进货状态 已完成
            bdmCloudInventoryItem.setMoney(new BigDecimal("0"));//本次金额
            bdmCloudInventoryItem.setStockTime(nowDate);// 进货时间
            bdmCloudInventoryItem.setCreateTime(nowDate);//创建时间
            bdmCloudInventoryItem.setCreateBy(loginUser.getUserId().toString());//创建用户
            bdmCloudInventoryItem.setUpdateTime(nowDate);//修改时间
            bdmCloudInventoryItem.setUpdateBy(loginUser.getUserId().toString());//修改用户
            bdmCloudInventoryItemService.save(bdmCloudInventoryItem);
            bdmCloudInventoryItems.add(bdmCloudInventoryItem);
        }
        this.addOrRollBackByCloudInventoryItem(bdmCloudInventoryItems);//通过 云库存明细 进行 增加或者减少 对应地方的库存
        return true;
    }

    /**
     * 查询我的云库存列表
     */
    @Override
    public AppletCloudInventoryVo listByUser() {

        Long userId = SecurityUtils.getUserId();
        List<BdmCloudInventory> bdmCloudInventories = bdmCloudInventoryMapper.appletListAgencyInventoryById(userId);
        AppletCloudInventoryVo appletCloudInventoryVo = new AppletCloudInventoryVo();
        appletCloudInventoryVo.setBdmCloudInventoryList(bdmCloudInventories);
        Long aLong = 0L;
        if (!CollectionUtils.isEmpty(bdmCloudInventories)) {
            aLong = bdmCloudInventories.stream().map(item -> Long.parseLong(item.getGoodInventory())).reduce(Long::sum).get();
        }
        appletCloudInventoryVo.setConuntInventory(aLong);
        return appletCloudInventoryVo;
    }

    /**
     * 查询代理库存详情
     */
    @Override
    public List<BdmCloudInventory> listAgencyInventoryById(Long userId) {
        return bdmCloudInventoryMapper.listAgencyInventoryById(userId);
    }

    /**
     * 查询云库存明细
     */
    @Override
    public List<BdmCloudInventoryItem> listByCloudInventoryId(BdmCloudInventoryItemDto bdmCloudInventoryItemDto) {
        Long userId = SecurityUtils.getUserId();
        return bdmCloudInventoryItemService.lambdaQuery()
                .eq(BdmCloudInventoryItem::getUserId, userId)
                .eq(ObjectUtils.isNotEmpty(bdmCloudInventoryItemDto.getCloudInventoryId()),
                        BdmCloudInventoryItem::getCloudInventoryId,
                        bdmCloudInventoryItemDto.getCloudInventoryId())
                .like(ObjectUtils.isNotEmpty(bdmCloudInventoryItemDto.getStartDate()),
                        BdmCloudInventoryItem::getCreateTime,
                        bdmCloudInventoryItemDto.getStartDate())
                .eq(ObjectUtils.isNotEmpty(bdmCloudInventoryItemDto.getNumType()),
                        BdmCloudInventoryItem::getNumType,
                        bdmCloudInventoryItemDto.getNumType())
                .orderByDesc(BdmCloudInventoryItem::getCreateTime)
                .list();
    }


    /**
     * 后台查询云库存明细
     */
    @Override
    public List<BdmCloudInventoryItemVo> cloudInventoryDetail(CloudInventoryDetailDto cloudInventoryDetailDto) {

        return bdmCloudInventoryItemService.cloudInventoryDetail(cloudInventoryDetailDto);
    }

    /**
     * 查询库存扣减类型
     */
    @Override
    public List<String> getInventoryDeductionType() {
        return bdmCloudInventoryMapper.getInventoryDeductionType();
    }

    /**
     * 云库存进货
     */
    @Override
    @Transactional
    public boolean cloudInventoryPurchase(CloudInventoryPurchaseDto cloudInventoryPurchaseDto) {
        //登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //当前日期
        Date nowDate = DateUtils.getNowDate();
        //补货商品
        BdmGood bdmGood = bdmGoodService.lambdaQuery().eq(BdmGood::getId, cloudInventoryPurchaseDto.getGoodId()).one();
        if (ObjectUtils.isEmpty(bdmGood)) {
            throw new RuntimeException("商品不存在");
        }
        //当前用户
        BdmUser bdmUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, loginUser.getUserId()).one();

        //当前用户等级
        BdmMemberRule bdmMemberRule = bdmMemberRuleService.lambdaQuery().eq(BdmMemberRule::getSysUserid, loginUser.getUserId()).one();

        //扣减商品库存
        ArrayList<BdmOrderItem> bdmOrderItems = new ArrayList<>();
        BdmOrderItem bdmOrderItem = new BdmOrderItem();
        bdmOrderItem.setSupplierGoodId(cloudInventoryPurchaseDto.getGoodId().toString());//商品id
        bdmOrderItem.setGoodCount(cloudInventoryPurchaseDto.getGoodNum().toString());//商品数量
        bdmOrderItems.add(bdmOrderItem);
        bdmGoodService.addOrRollBackStock(bdmOrderItems, BdmGoodEnum.SUB.getType());
        //查询有没有此商品的云库存如果没有就创建一个
        BdmCloudInventory item = this.lambdaQuery()
                .eq(BdmCloudInventory::getUserId, loginUser.getUserId())//用户id
                .eq(BdmCloudInventory::getGoodId, cloudInventoryPurchaseDto.getGoodId())//商品id
                .one();

        //填充日期创建用户
        BdmCloudInventory bdmCloudInventory = new BdmCloudInventory();
        if (ObjectUtils.isNotEmpty(item)) {
            BeanUtil.copyProperties(item, bdmCloudInventory);
            bdmCloudInventory.setUpdateBy(loginUser.getUserId().toString());
            bdmCloudInventory.setUpdateTime(DateUtils.getNowDate());
        } else {
            bdmCloudInventory.setCreateTime(nowDate);
            bdmCloudInventory.setCreateBy(loginUser.getUserId().toString());
            bdmCloudInventory.setUpdateBy(loginUser.getUserId().toString());
            bdmCloudInventory.setUpdateTime(nowDate);
        }
        bdmCloudInventory.setGoodId(bdmGood.getId());//商品id
        bdmCloudInventory.setUserId(loginUser.getUserId());//用户id
        if (ObjectUtils.isNotEmpty(bdmGood.getProductLevel()) && bdmGood.getProductLevel() > BdmMemberRuleEnum.SVIP.getLevel()) {   //如果商品有等级 进货价就是售价
            bdmCloudInventory.setStockPrice(bdmGood.getRetailPrice());//进货价
        } else { //根据当前用户等级来
            //保底价格
            bdmCloudInventory.setStockPrice(bdmGood.getRetailPrice());//进货价

            if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberLevel()) && bdmMemberRule.getMemberLevel().equals(BdmMemberRuleEnum.VIP.getLevel())) { //vip
                bdmCloudInventory.setStockPrice(bdmGood.getVipPrice());//进货价
            }
            if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberLevel()) && bdmMemberRule.getMemberLevel().equals(BdmMemberRuleEnum.SVIP.getLevel())) {//svip
                bdmCloudInventory.setStockPrice(bdmGood.getSvipPrice());//进货价
            }
            if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.SHOPKEEPER.getLevel())) {//共享
                bdmCloudInventory.setStockPrice(bdmGood.getSharePrice());//进货价
            }
            if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.LAIN_CHANG.getLevel())) {//联创
                bdmCloudInventory.setStockPrice(bdmGood.getJoinPrice());//进货价
            }
            if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.OPERATION.getLevel())) {//运营
                bdmCloudInventory.setStockPrice(bdmGood.getOperationsPrice());//进货价
            }
            if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.BOSS.getLevel())) {//总裁
                bdmCloudInventory.setStockPrice(bdmGood.getPresidentPrice());//进货价
            }
        }
        bdmCloudInventory.setRetailPrice(bdmGood.getRetailPrice());//售价
        bdmCloudInventory.setProfit(bdmCloudInventory.getRetailPrice().subtract(bdmCloudInventory.getStockPrice()));//利润
        bdmCloudInventory.setGoodInventory(String.valueOf(ObjectUtils.isEmpty(bdmCloudInventory.getGoodInventory()) ? cloudInventoryPurchaseDto.getGoodNum() : Long.parseLong(bdmCloudInventory.getGoodInventory()) + cloudInventoryPurchaseDto.getGoodNum()));//库存
        bdmCloudInventory.setGoodImg(bdmGood.getGoodImg());//商品主图
        bdmCloudInventory.setGoodName(bdmGood.getGoodName());//商品名称
        bdmCloudInventory.setGoodSpecs(bdmGood.getGoodSpecs());//商品规格
        //添加或者修改云库存
        this.saveOrUpdate(bdmCloudInventory);

        //补货金额
        BigDecimal multiply = bdmCloudInventory.getStockPrice().multiply(new BigDecimal(cloudInventoryPurchaseDto.getGoodNum()));
        //扣钱
        if (cloudInventoryPurchaseDto.getPayType().equals(BdmOrderEnum.BALANCE.getType())) {//TODO 余额  暂时只有余额
            //扣减余额
            bdmUser.setRemainingSum(bdmUser.getRemainingSum().subtract(multiply));
            bdmUserService.updateById(bdmUser);
            //插入余额变动表
            BdmBalanceChange bdmBalanceChange = BdmBalanceChange.getBdmBalanceChange(
                    loginUser.getUserId(),
                    ObjectUtils.isEmpty(bdmCloudInventory) ? null : bdmCloudInventory.getId().toString(),
                    multiply.toString(),
                    bdmUser.getRemainingSum().toString(),
                    bdmUser.getRemainingSum().subtract(multiply).toString(),
                    Long.parseLong(BdmBalanceChangeEnum.BALANCE.getType()),
                    Long.parseLong(BdmBalanceChangeEnum.SUBTRACT.getType()),
                    BdmBalanceChangeEnum.CLOUD_INVENTORY_REPLENISHMENT.getDescription()
            );
            bdmBalanceChangeService.save(bdmBalanceChange);
        } else if (cloudInventoryPurchaseDto.getPayType().equals(BdmOrderEnum.THIRD_PARTY.getType())) {
            if (StringUtils.isEmpty(cloudInventoryPurchaseDto.getId())) {
                throw new RuntimeException("支付订单号必填");
            }
            BdmOrder bdmOrder = new BdmOrder();
            bdmOrder.setId(cloudInventoryPurchaseDto.getId());
            bdmPayService.selectPay(bdmOrder);
        }


        //查询当前用户有没有上级  有上级先找上级购买
        BdmCloudInventoryItem bdmCloudInventoryItem = new BdmCloudInventoryItem();

        //TODO  查询等级比自己高的上级
        Long parentId = getParent(bdmUser, bdmMemberRule);
        if (ObjectUtils.isEmpty(parentId) || parentId.equals(0L)) {//没上级商城买
            //云库存明细对象
            bdmCloudInventoryItem.setCloudInventoryId(bdmCloudInventory.getId());//云库存id
            bdmCloudInventoryItem.setGoodId(bdmGood.getId());//商品id
            bdmCloudInventoryItem.setGoodName(bdmGood.getGoodName());//商品名称
            bdmCloudInventoryItem.setGoodImg(bdmGood.getGoodImg());//商品图片
            bdmCloudInventoryItem.setNum(cloudInventoryPurchaseDto.getGoodNum());//商品数量
            bdmCloudInventoryItem.setNumType(BdmCloudInventoryEnum.NUM_TYPE_ADD.getType());//数量类型   加
            bdmCloudInventoryItem.setVariationType(BdmCloudInventoryEnum.MALL_PURCHASE.getDescription());// 变动类型 商城购买
            bdmCloudInventoryItem.setUserId(loginUser.getUserId());//用户id
            bdmCloudInventoryItem.setCorrelationUserId(0L);//补货上下级  平台
            bdmCloudInventoryItem.setStockType(BdmCloudInventoryEnum.IN_STOCK.getType());//进货状态 进货中
            bdmCloudInventoryItem.setMoney(multiply);//本次金额
            bdmCloudInventoryItem.setStockTime(nowDate);//进货时间
            bdmCloudInventoryItem.setRelevantDocumentId(cloudInventoryPurchaseDto.getId());//相关单据id
            bdmCloudInventoryItem.setCreateTime(nowDate);//创建时间
            bdmCloudInventoryItem.setCreateBy(loginUser.getUserId().toString());//创建用户
            bdmCloudInventoryItem.setUpdateTime(nowDate);//修改时间
            bdmCloudInventoryItem.setUpdateBy(loginUser.getUserId().toString());//修改用户

        } else {//有上级走递归

            //查询上级云库存是否有货
            BdmCloudInventory one = this.lambdaQuery()
                    .eq(BdmCloudInventory::getUserId, parentId)
                    .eq(BdmCloudInventory::getGoodId, bdmGood.getId())
                    .ge(BdmCloudInventory::getGoodInventory, cloudInventoryPurchaseDto.getGoodNum()).one();

            //TODO 增加上级的 收益
            BdmUser parentBdmUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, parentId).one();
            SysUser sysUser = sysUserService.selectUserById(parentBdmUser.getSysUserid());
            if (ObjectUtils.isNotEmpty(parentBdmUser) && ObjectUtils.isNotEmpty(sysUser)) {
                BigDecimal earnings = parentBdmUser.getEarnings();
                BigDecimal sum = earnings.add(multiply);
                parentBdmUser.setEarnings(sum);
                bdmUserService.updateById(parentBdmUser);
                //记录佣金变动
                BdmBalanceChange bdmBalanceChange = new BdmBalanceChange();
                bdmBalanceChange.setUserId(sysUser.getUserId());
                bdmBalanceChange.setUserPhone(sysUser.getPhonenumber());
                bdmBalanceChange.setNickName(sysUser.getNickName());
                bdmBalanceChange.setRelevantDocumentId(bdmCloudInventory.getId().toString());
                bdmBalanceChange.setVariation(multiply.toString());
                bdmBalanceChange.setVariationBefore(earnings.toString());
                bdmBalanceChange.setVariationAfter(sum.toString());
                bdmBalanceChange.setVariationType(Long.parseLong(BdmBalanceChangeEnum.BROKERAGE.getType()));
                bdmBalanceChange.setAddOrSubtract(Long.parseLong(BdmBalanceChangeEnum.ADD.getType()));
                bdmBalanceChange.setBusinessType(BdmBalanceChangeEnum.LOWER_LEVEL_PURCHASES_OF_CLOUD_INVENTORY_ITEMS.getDescription());
                bdmBalanceChange.setCreateTime(nowDate);
                bdmBalanceChangeService.insertBdmBalanceChange(bdmBalanceChange);
            }


            bdmCloudInventoryItem.setCloudInventoryId(bdmCloudInventory.getId());//云库存id
            bdmCloudInventoryItem.setGoodId(bdmGood.getId());//商品id
            bdmCloudInventoryItem.setGoodName(bdmGood.getGoodName());//商品名称
            bdmCloudInventoryItem.setGoodImg(bdmGood.getGoodImg());//商品图片
            bdmCloudInventoryItem.setNum(cloudInventoryPurchaseDto.getGoodNum());//商品数量
            bdmCloudInventoryItem.setNumType(BdmCloudInventoryEnum.NUM_TYPE_ADD.getType());//数量类型   加
            bdmCloudInventoryItem.setVariationType(BdmCloudInventoryEnum.GET_GOODS.getDescription());// 变动类型  找上级拿货
            bdmCloudInventoryItem.setUserId(loginUser.getUserId());//用户id
            bdmCloudInventoryItem.setCorrelationUserId(parentId);//补货上下级
            bdmCloudInventoryItem.setStockType(BdmCloudInventoryEnum.IN_STOCK.getType());//进货状态 进货中
            bdmCloudInventoryItem.setMoney(multiply);//本次金额
            bdmCloudInventoryItem.setRelevantDocumentId(cloudInventoryPurchaseDto.getId());//相关单据id
            bdmCloudInventoryItem.setStockTime(ObjectUtils.isEmpty(one) ? new Date(System.currentTimeMillis() + 1000 * 60 * 60 * BdmCloudInventoryEnum.STOCK_HOUR.getType()) : nowDate);//进货时间
            bdmCloudInventoryItem.setCreateTime(nowDate);//创建时间
            bdmCloudInventoryItem.setCreateBy(loginUser.getUserId().toString());//创建用户
            bdmCloudInventoryItem.setUpdateTime(nowDate);//修改时间
            bdmCloudInventoryItem.setUpdateBy(loginUser.getUserId().toString());//修改用户
        }
        bdmUser.setParentId(parentId);
        sendNote(bdmUser);
        bdmCloudInventoryItemService.save(bdmCloudInventoryItem);
        //添加云库存明细
        this.addBdmCloudInventoryItem(bdmCloudInventoryItem, bdmUser);


        return true;
    }

    /**
     * 补货查看商品详情
     */
    @Override
    public CommodityDetailsVo getCommodityDetails(Long goodId) {
        return bdmGoodService.getCommodityDetails(goodId);
    }

    /**
     * 云库存提货到线下
     */
    @Override
    @Transactional
    public String cloudInventoryPickup(CloudInventoryPickupDto cloudInventoryPickupDto) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        StringJoiner goodNamesJoiner = new StringJoiner(";");
        List<ColudInventoryGoodDto> coludInventoryGoodDtos = cloudInventoryPickupDto.getColudInventoryGoodDtos();
        for (ColudInventoryGoodDto coludInventoryGoodDto : coludInventoryGoodDtos) {
            //查询是否有云库存
            BdmCloudInventory bdmCloudInventory = this.lambdaQuery()
                    .eq(BdmCloudInventory::getUserId, user.getUserId())
                    .eq(BdmCloudInventory::getGoodId, coludInventoryGoodDto.getGoodId())
                    .ge(BdmCloudInventory::getGoodInventory, coludInventoryGoodDto.getGoodNum()).one();
            if (ObjectUtils.isEmpty(bdmCloudInventory)) {
                BdmGood bdmGood = bdmGoodService.lambdaQuery().eq(BdmGood::getId, coludInventoryGoodDto.getGoodId()).one();
                throw new RuntimeException("商品《" + bdmGood.getGoodName() + "》库存不足");
            }
            goodNamesJoiner.add(bdmCloudInventory.getGoodName());
        }
        String goodNames = goodNamesJoiner.toString();



        BdmReceiveAddress bdmReceiveAddress = cloudInventoryPickupDto.getBdmReceiveAddress();
        StringBuilder addr = new StringBuilder();
        //省
        if (StringUtils.isNotEmpty(bdmReceiveAddress.getProvince())) {
            addr.append(bdmReceiveAddress.getProvince());
        }
        //市
        if (StringUtils.isNotEmpty(bdmReceiveAddress.getCity())) {
            addr.append(bdmReceiveAddress.getCity());
        }
        //区
        if (StringUtils.isNotEmpty(bdmReceiveAddress.getDistrict())) {
            addr.append(bdmReceiveAddress.getDistrict());
        }
        //详细地址
        if (StringUtils.isNotEmpty(bdmReceiveAddress.getDetail())) {
            addr.append(bdmReceiveAddress.getDetail());
        }
        //创建订单 订单项  扣减云库存  发货
        BdmOrder bdmOrder = BdmOrder.builder()
                .id(bdmOrderService.generateOrderNumber())//订单id
                .userId(user.getUserId())//用户id
                .userName(user.getUserName())//姓名
                .phoneNumber(user.getPhonenumber())//用户手机号
                .payMoney(cloudInventoryPickupDto.getCostPrice().toString())//实付金额
                .deliveryCost(cloudInventoryPickupDto.getCostPrice().toString())//配送费 TODO  目前配送费写死后期需要在后台设置
                .receiveName(bdmReceiveAddress.getRealName())//收货人姓名
                .receiveAddress(addr.toString()) //地址
                .receivePhonenum(bdmReceiveAddress.getPhone())//收货人电话
                .receiveLongitude(bdmReceiveAddress.getLongitude())//经度
                .receiveLatitude(bdmReceiveAddress.getLatitude())//纬度
                .createTime(DateUtils.getNowDate()) //创建时间
                .deductIntegral("0")//本单扣除积分
                .gainIntegral("0")//本单获取积分
                .goodNames(goodNames)
                .orderStatus(BdmOrderEnum.UNPAID.getType())//待支付状态
                .remark(cloudInventoryPickupDto.getRemark())//留言
                .orderType(BdmGoodEnum.CLOUD_INVENTORY_ORDER.getType())//订单类型 云库存订单
//                .payType(BdmOrderEnum.CLOUD_INVENTORY_PICKUP.getType())//支付类型 云库存提货
                .build();
        //新增订单
        bdmOrderService.save(bdmOrder);

        Date nowDate = DateUtils.getNowDate();
        for (ColudInventoryGoodDto coludInventoryGoodDto : coludInventoryGoodDtos) {

            //商品
            BdmGood bdmGood = bdmGoodService.lambdaQuery().eq(BdmGood::getId, coludInventoryGoodDto.getGoodId()).one();
            //云库存
            BdmCloudInventory bdmCloudInventory = this.lambdaQuery()
                    .eq(BdmCloudInventory::getUserId, user.getUserId())
                    .eq(BdmCloudInventory::getGoodId, coludInventoryGoodDto.getGoodId()).one();


            //新增订单项
            BdmOrderItem bdmOrderItem = BdmOrderItem.builder()
                    .orderId(bdmOrder.getId())//订单id
                    .goodTypeId(bdmGood.getClassOneId())//商品类型id
                    .goodTypeName(bdmGood.getClassOneName())//商品类型名称
                    .supplierGoodId(bdmGood.getId().toString())//供应商商品id
                    .goodName(bdmGood.getGoodName())//商品名称
                    .goodPrice(new BigDecimal("0"))//价格
                    .goodCount(coludInventoryGoodDto.getGoodNum().toString())//数量
                    .gainIntegral("0")//此项获取积分
                    .deductIntegral("0")//此项扣除积分
                    .remarks("")
                    .build();
            bdmOrderItemService.save(bdmOrderItem);

            //扣减自己云库存
            ArrayList<BdmCloudInventoryItem> items = new ArrayList<>();
            BdmCloudInventoryItem bdmCloudInventoryItem = new BdmCloudInventoryItem();

            bdmCloudInventoryItem.setCloudInventoryId(bdmCloudInventory.getId());//云库存id
            bdmCloudInventoryItem.setGoodId(bdmGood.getId());//商品id
            bdmCloudInventoryItem.setGoodName(bdmGood.getGoodName());//商品名称
            bdmCloudInventoryItem.setGoodImg(bdmGood.getGoodImg());//商品图片
            bdmCloudInventoryItem.setNum(coludInventoryGoodDto.getGoodNum());//商品数量
            bdmCloudInventoryItem.setNumType(BdmCloudInventoryEnum.NUM_TYPE_SUB.getType());//数量类型   减少
            bdmCloudInventoryItem.setVariationType(BdmCloudInventoryEnum.TAKE_THE_GOODS_BY_ONESELF.getDescription());// 自提货到线下
            bdmCloudInventoryItem.setUserId(user.getUserId());//用户id
            bdmCloudInventoryItem.setCorrelationUserId(user.getUserId());//补货上下级  自己
            bdmCloudInventoryItem.setStockType(BdmCloudInventoryEnum.ACCOMPLISH.getType());//进货状态 已完成
            bdmCloudInventoryItem.setMoney(new BigDecimal("0"));//进货状态 已完成
            bdmCloudInventoryItem.setStockTime(nowDate);//进货时间
            bdmCloudInventoryItem.setCreateTime(nowDate);//创建时间
            bdmCloudInventoryItem.setRelevantDocumentId(bdmOrder.getId());
            bdmCloudInventoryItem.setCreateBy(user.getUserId().toString());//创建用户
            bdmCloudInventoryItem.setUpdateTime(nowDate);//修改时间
            bdmCloudInventoryItem.setUpdateBy(user.getUserId().toString());//修改用户

            items.add(bdmCloudInventoryItem);
            this.addOrRollBackStock(items, BdmCloudInventoryEnum.SUB.getType());
            //记录云库存明细
            bdmCloudInventoryItemService.saveBatch(items);
        }

        return bdmOrder.getId();
    }


    @Override
    @Transactional
    public AjaxResult cloudInventory(BdmOrderDto bdmOrderDto) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        BdmCloudInventoryItem bdmCloudInventoryItem1 = new BdmCloudInventoryItem();
        bdmCloudInventoryItem1.setRelevantDocumentId(bdmOrderDto.getOrderId());
        Date nowDate = DateUtils.getNowDate();
        List<BdmCloudInventoryItem> bdmCloudInventoryItems = bdmCloudInventoryItemService.selectBdmCloudInventoryItemList(bdmCloudInventoryItem1);
        for (BdmCloudInventoryItem bdmCloudInventoryItem2 : bdmCloudInventoryItems) {
            //扣减自己云库存
            ArrayList<BdmCloudInventoryItem> items = new ArrayList<>();
            BdmCloudInventoryItem bdmCloudInventoryItem = new BdmCloudInventoryItem();

            bdmCloudInventoryItem.setCloudInventoryId(bdmCloudInventoryItem2.getCloudInventoryId());//云库存id
            bdmCloudInventoryItem.setGoodId(bdmCloudInventoryItem2.getGoodId());//商品id
            bdmCloudInventoryItem.setGoodName(bdmCloudInventoryItem2.getGoodName());//商品名称
            bdmCloudInventoryItem.setGoodImg(bdmCloudInventoryItem2.getGoodImg());//商品图片
            bdmCloudInventoryItem.setNum(bdmCloudInventoryItem2.getNum());//商品数量
            bdmCloudInventoryItem.setNumType(BdmCloudInventoryEnum.NUM_TYPE_ADD.getType());//数量类型   减少
            bdmCloudInventoryItem.setVariationType(BdmCloudInventoryEnum.TAKE_DELIVERY_REQUEST_RETURN.getDescription());// 自提货到线下
            bdmCloudInventoryItem.setUserId(user.getUserId());//用户id
            bdmCloudInventoryItem.setCorrelationUserId(user.getUserId());//补货上下级  自己
            bdmCloudInventoryItem.setStockType(BdmCloudInventoryEnum.ACCOMPLISH.getType());//进货状态 已完成
            bdmCloudInventoryItem.setMoney(new BigDecimal("0"));//进货状态 已完成
            bdmCloudInventoryItem.setStockTime(nowDate);//进货时间
            bdmCloudInventoryItem.setCreateTime(nowDate);//创建时间
            bdmCloudInventoryItem.setCreateBy(user.getUserId().toString());//创建用户
            bdmCloudInventoryItem.setUpdateTime(nowDate);//修改时间
            bdmCloudInventoryItem.setUpdateBy(user.getUserId().toString());//修改用户

            items.add(bdmCloudInventoryItem);
            log.info("云库存明细：{}", items);
            this.addOrRollBackStock(items, BdmCloudInventoryEnum.ADD.getType());
            //记录云库存明细
            bdmCloudInventoryItemService.saveBatch(items);
        }
        BdmOrder bdmOrder = bdmOrderService.selectBdmOrderById(bdmOrderDto.getOrderId());
        bdmOrder.setOrderStatus(BdmOrderEnum.CLOSE.getType());
        bdmOrderService.updateById(bdmOrder);
        return AjaxResult.success();
    }

    /**
     * 云库存余额支付
     * @param orderId
     * @return
     */
    @Override
    @Transactional
    public AjaxResult payCloudInventoryOrder(String orderId) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        BdmUser bdmUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, user.getUserId()).one();
        BdmOrder bdmOrder = bdmOrderService.selectBdmOrderById(orderId);
        BigDecimal remainingSum = bdmUser.getRemainingSum();
        List<BdmBalanceChange> bdmBalanceChanges = new ArrayList<>();
        //判断余额
        if (remainingSum.compareTo(new BigDecimal(bdmOrder.getPayMoney())) < 0) {
            throw new RuntimeException("账户余额不足");
        }
        bdmBalanceChanges.add(BdmBalanceChange.getBdmBalanceChange(
                user.getUserId(),
                bdmOrder.getId(),
                bdmOrder.getPayMoney(),
                remainingSum.toString(),
                String.valueOf(remainingSum.subtract(new BigDecimal(bdmOrder.getPayMoney()))),
                Long.parseLong(BdmBalanceChangeEnum.BALANCE.getType()),
                Long.parseLong(BdmBalanceChangeEnum.SUBTRACT.getType()),
                BdmBalanceChangeEnum.CONSUMPTION_DEDUCTION.getDescription()
        ));
        bdmBalanceChangeService.saveBatch(bdmBalanceChanges);
        bdmOrder.setOrderStatus(BdmOrderEnum.SHIPMENTS.getType());
        bdmOrder.setPayType(BdmOrderEnum.BALANCE.getType());
        bdmOrder.setPaymentTime(DateUtils.getNowDate());
        bdmOrderService.updateById(bdmOrder);
        bdmUser.setRemainingSum(bdmUser.getRemainingSum().subtract(new BigDecimal(bdmOrder.getPayMoney())));
        bdmUserService.updateById(bdmUser);
        //聚水潭发货
        List<BdmOrderItemVo> bdmOrderItemVos = bdmOrderItemService.getBdmOrderItems(bdmOrder.getId());
        //发货
        bdmOrderService.deliverGoods(bdmOrderItemVos, bdmOrder, BdmOrderEnum.BALANCE.getDescription());
        return AjaxResult.success(orderId);
    }


    /**
     * 云仓补货查询用户
     */
    @Override
    public SysUser getUser(Long userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return new SysUser();
        }
        BdmMemberRule one = bdmMemberRuleService.lambdaQuery().eq(BdmMemberRule::getSysUserid, userId)
                .ge(BdmMemberRule::getMemberAgencyLevel, BdmMemberRuleEnum.SHOPKEEPER.getLevel())
                .one();
        if (ObjectUtils.isEmpty(one)) {
            return new SysUser();
        }
        return sysUserService.selectUserById(userId);
    }


    /**
     * 云仓配货
     */
    @Override
    public String cloudWarehouseReplenishment(BdmCloudReplenishmentDto dto) {

        SysUser user = SecurityUtils.getLoginUser().getUser();
        //原用户云库存
        BdmCloudInventory bdmCloudInventory = this.lambdaQuery()
                .eq(BdmCloudInventory::getId, dto.getId())
                .eq(BdmCloudInventory::getUserId, user.getUserId()).one();


        //查询这个云库存是否属于自己
        if (ObjectUtils.isEmpty(bdmCloudInventory)) {
            throw new RuntimeException("云库存不存在,请先补货。");
        }
        //判断数量
        if (dto.getNum() > Long.parseLong(bdmCloudInventory.getGoodInventory())) {
            throw new RuntimeException("云库存数量不足");
        }

        // 不能给自己配货
        if (SecurityUtils.getUserId().equals(dto.getUserId())) {
            throw new RuntimeException("不能给自己配货");
        }

        BdmGood bdmGood = bdmGoodService.lambdaQuery().eq(BdmGood::getId, bdmCloudInventory.getGoodId()).one();
        if (ObjectUtils.isEmpty(bdmGood)) {
            throw new RuntimeException("商品不存在");
        }

        BdmMemberRule bdmMemberRule = bdmMemberRuleService.lambdaQuery().eq(BdmMemberRule::getSysUserid, dto.getUserId()).one();
        if (ObjectUtils.isEmpty(bdmMemberRule)) {
            throw new RuntimeException("被配货用户不存在");
        }

        //公共参数
        Date nowDate = DateUtils.getNowDate();
        List<BdmCloudInventory> bdmCloudInventories = new ArrayList<>();
        List<BdmCloudInventoryItem> bdmCloudInventoryItems = new ArrayList<>();


        //原用户 总数量
        BigDecimal yUserNum = new BigDecimal(bdmCloudInventory.getGoodInventory());
        //配货数量
        BigDecimal num = new BigDecimal(dto.getNum().toString());

        //扣减原用户 云库存
        bdmCloudInventory.setGoodInventory(yUserNum.subtract(num).toString());
        //记录原用户 云库存明细
        BdmCloudInventoryItem bdmCloudInventoryItem = new BdmCloudInventoryItem();
        bdmCloudInventoryItem.setCloudInventoryId(bdmCloudInventory.getId());
        bdmCloudInventoryItem.setGoodId(bdmCloudInventory.getGoodId());
        bdmCloudInventoryItem.setGoodName(bdmCloudInventory.getGoodName());
        bdmCloudInventoryItem.setGoodImg(bdmCloudInventory.getGoodImg());
        bdmCloudInventoryItem.setNum(Long.parseLong(num.toString()));
        bdmCloudInventoryItem.setNumType(BdmCloudInventoryEnum.NUM_TYPE_SUB.getType());
        bdmCloudInventoryItem.setVariationType(BdmCloudInventoryEnum.CLOUD_DISTRIBUTION_SUB.getDescription());
        bdmCloudInventoryItem.setUserId(user.getUserId());
        bdmCloudInventoryItem.setCorrelationUserId(dto.getUserId());
        bdmCloudInventoryItem.setCreateBy(user.getUserId().toString());
        bdmCloudInventoryItem.setCreateTime(nowDate);
        bdmCloudInventoryItem.setStockType(BdmCloudInventoryEnum.ACCOMPLISH.getType());
        bdmCloudInventoryItem.setStockTime(nowDate);
        bdmCloudInventoryItem.setMoney(new BigDecimal("0"));
        bdmCloudInventories.add(bdmCloudInventory);
        bdmCloudInventoryItems.add(bdmCloudInventoryItem);

        //查询被补货用户是否有云库存
        BdmCloudInventory newBdmCloudInventory = this.lambdaQuery()
                .eq(BdmCloudInventory::getGoodId, bdmCloudInventory.getGoodId())
                .eq(BdmCloudInventory::getUserId, dto.getUserId())
                .one();


        //新增库存
        BdmCloudInventory item = new BdmCloudInventory();
        BeanUtil.copyProperties(newBdmCloudInventory, item);

        item.setUserId(dto.getUserId());
        item.setGoodId(bdmCloudInventory.getGoodId());
        item.setGoodName(bdmCloudInventory.getGoodName());
        item.setGoodImg(bdmCloudInventory.getGoodImg());
        //保底价格
        item.setStockPrice(bdmGood.getRetailPrice());//进货价
        if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberLevel()) && bdmMemberRule.getMemberLevel().equals(BdmMemberRuleEnum.VIP.getLevel())) { //vip
            item.setStockPrice(bdmGood.getVipPrice());//进货价
        }
        if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberLevel()) && bdmMemberRule.getMemberLevel().equals(BdmMemberRuleEnum.SVIP.getLevel())) {//svip
            item.setStockPrice(bdmGood.getSvipPrice());//进货价
        }
        if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.SHOPKEEPER.getLevel())) {//共享
            item.setStockPrice(bdmGood.getSharePrice());//进货价
        }
        if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.LAIN_CHANG.getLevel())) {//联创
            item.setStockPrice(bdmGood.getJoinPrice());//进货价
        }
        if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.OPERATION.getLevel())) {//运营
            item.setStockPrice(bdmGood.getOperationsPrice());//进货价
        }
        if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.BOSS.getLevel())) {//总裁
            item.setStockPrice(bdmGood.getPresidentPrice());//进货价
        }
        item.setRetailPrice(bdmGood.getRetailPrice());
        item.setProfit(bdmGood.getRetailPrice().subtract(item.getStockPrice()));

        item.setGoodInventory(StringUtils.isEmpty(item.getGoodInventory()) ? num.toString() : new BigDecimal(item.getGoodInventory()).add(num).toString());
        item.setGoodSpecs(bdmGood.getGoodSpecs());

        //新增云库存获取自增长id
        if (ObjectUtils.isEmpty(newBdmCloudInventory)) {
            this.insertBdmCloudInventory(item);
        } else {
            bdmCloudInventories.add(item);
        }

        //新增云库存明细
        //记录原用户 云库存明细
        BdmCloudInventoryItem newBdmCloudInventoryItem = new BdmCloudInventoryItem();
        newBdmCloudInventoryItem.setCloudInventoryId(item.getId());
        newBdmCloudInventoryItem.setGoodId(item.getGoodId());
        newBdmCloudInventoryItem.setGoodName(item.getGoodName());
        newBdmCloudInventoryItem.setGoodImg(item.getGoodImg());
        newBdmCloudInventoryItem.setNum(Long.parseLong(num.toString()));
        newBdmCloudInventoryItem.setNumType(BdmCloudInventoryEnum.NUM_TYPE_ADD.getType());
        newBdmCloudInventoryItem.setVariationType(BdmCloudInventoryEnum.CLOUD_DISTRIBUTION_ADD.getDescription());
        newBdmCloudInventoryItem.setUserId(dto.getUserId());
        newBdmCloudInventoryItem.setCorrelationUserId(user.getUserId());
        newBdmCloudInventoryItem.setCreateBy(user.getUserId().toString());
        newBdmCloudInventoryItem.setCreateTime(nowDate);
        newBdmCloudInventoryItem.setStockType(BdmCloudInventoryEnum.ACCOMPLISH.getType());
        newBdmCloudInventoryItem.setStockTime(nowDate);
        newBdmCloudInventoryItem.setMoney(new BigDecimal("0"));
        bdmCloudInventoryItems.add(newBdmCloudInventoryItem);


        //修改云库存
        this.saveOrUpdateBatch(bdmCloudInventories);
        //记录库存明细
        bdmCloudInventoryItemService.saveOrUpdateBatch(bdmCloudInventoryItems);

        return "操作成功";
    }

    /**
     * 查询云库存代理商
     *
     * @param dto
     * @return
     */
    @Override
    public AjaxResult listAgencyInventoryByUserId(BdmCloudInventoryDto dto) {
        Integer pageNum1 = dto.getPageNum();
        Integer pageSize1 = dto.getPageSize();
        dto.setPageNum(null);
        dto.setPageSize(null);

        // 查询所有下级（递归查询或数据库查询）
        // 这里假设 listAgencyInventoryByUserId 已经返回了当前用户的所有下级，不分级
        List<AgencyInventoryVo> allAgencyInventoryVos = bdmCloudInventoryMapper.listAgencyInventoryByUserId(dto);

        // 内存分页
        int total = allAgencyInventoryVos.size();
        int pageNum = pageNum1 == null ? 1 : pageNum1;
        int pageSize = pageSize1 == null ? 10 : pageSize1;
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);

        List<AgencyInventoryVo> pagedList = new ArrayList<>();
        if (fromIndex < total) {
            pagedList = allAgencyInventoryVos.subList(fromIndex, toIndex);
        }

        // 返回分页结果
        return AjaxResult.success()
                .put("total", total)
                .put("pageNum", pageNum)
                .put("pageSize", pageSize)
                .put("rows", pagedList);

    }

    /**
     * 根据 云库存明细  扣除库存 或者 回滚库存
     */
    public void addOrRollBackByCloudInventoryItem(List<BdmCloudInventoryItem> bdmCloudInventoryItems) {
        for (BdmCloudInventoryItem bdmCloudInventoryItem : bdmCloudInventoryItems) {
            if (bdmCloudInventoryItem.getStockType().equals(BdmCloudInventoryEnum.ACCOMPLISH.getType())) {//已完成的
                //商城购买  库存已经从商城扣除过 只用增加云库存
                if (bdmCloudInventoryItem.getVariationType().equals(BdmCloudInventoryEnum.MALL_PURCHASE.getDescription())) {
                    ArrayList<BdmCloudInventoryItem> items = new ArrayList<>();
                    items.add(bdmCloudInventoryItem);
                    //TODO  客户要求付款 直接增加云库存
                    //addOrRollBackStock(items, BdmCloudInventoryEnum.ADD.getType());
                    // 找上级拿货   增加自己云库存
                } else if (bdmCloudInventoryItem.getVariationType().equals(BdmCloudInventoryEnum.GET_GOODS.getDescription())) {
                    ArrayList<BdmCloudInventoryItem> items = new ArrayList<>();
                    items.add(bdmCloudInventoryItem);
                    //TODO  客户要求付款 直接增加云库存
                    //addOrRollBackStock(items, BdmCloudInventoryEnum.ADD.getType());
                    // 被下级进货  减少自己云库存 回滚商品库存
                } else if (bdmCloudInventoryItem.getVariationType().equals(BdmCloudInventoryEnum.STOCK.getDescription())) {
                    //减自己
                    ArrayList<BdmCloudInventoryItem> items = new ArrayList<>();
                    items.add(bdmCloudInventoryItem);
                    addOrRollBackStock(items, BdmCloudInventoryEnum.SUB.getType());
                    //增加自己余额 减少自己佣金
                    bdmUserService.cloudInventoryIncreasesTheBalance(bdmCloudInventoryItem);
                    //回商品库存
                    ArrayList<BdmOrderItem> bdmOrderItems = new ArrayList<>();
                    BdmOrderItem bdmOrderItem = new BdmOrderItem();
                    bdmOrderItem.setSupplierGoodId(bdmCloudInventoryItem.getGoodId().toString());//商品id
                    bdmOrderItem.setGoodCount(bdmCloudInventoryItem.getNum().toString());//商品数量
                    bdmOrderItems.add(bdmOrderItem);
                    bdmGoodService.addOrRollBackStock(bdmOrderItems, BdmGoodEnum.ADD.getType());
                    //系统添加   增加自己云库存 减少商城库存
                } else if (bdmCloudInventoryItem.getVariationType().equals(BdmCloudInventoryEnum.SYSTEM_ADDITION.getDescription())) {
                    List<BdmOrderItem> bdmOrderItems = new ArrayList<>();
                    BdmOrderItem bdmOrderItem = new BdmOrderItem();
                    bdmOrderItem.setSupplierGoodId(bdmCloudInventoryItem.getGoodId().toString());
                    bdmOrderItem.setGoodCount(bdmCloudInventoryItem.getNum().toString());
                    bdmOrderItems.add(bdmOrderItem);
                    bdmGoodService.addOrRollBackStock(bdmOrderItems, BdmCloudInventoryEnum.SUB.getType()); //减少商品库存
                    ArrayList<BdmCloudInventoryItem> items = new ArrayList<>();
                    items.add(bdmCloudInventoryItem);
                    addOrRollBackStock(items, BdmCloudInventoryEnum.ADD.getType());   //增加增加云库存
                    //系统减少 减少自己云库存  增加商城库存
                } else if (bdmCloudInventoryItem.getVariationType().equals(BdmCloudInventoryEnum.SYSTEM_REDUCTION.getDescription())) {
                    List<BdmOrderItem> bdmOrderItems = new ArrayList<>();
                    BdmOrderItem bdmOrderItem = new BdmOrderItem();
                    bdmOrderItem.setSupplierGoodId(bdmCloudInventoryItem.getGoodId().toString());
                    bdmOrderItem.setGoodCount(bdmCloudInventoryItem.getNum().toString());
                    bdmOrderItems.add(bdmOrderItem);
                    bdmGoodService.addOrRollBackStock(bdmOrderItems, BdmCloudInventoryEnum.ADD.getType()); //增加商品库存
                    ArrayList<BdmCloudInventoryItem> items = new ArrayList<>();
                    items.add(bdmCloudInventoryItem);
                    addOrRollBackStock(items, BdmCloudInventoryEnum.SUB.getType());   //减少云库存
                }
            }
        }
    }

    private void sendNote(BdmUser bdmUser) {
        TencentSendNoTeRequest request = new TencentSendNoTeRequest();
        Long parentId = bdmUser.getParentId();
        BdmUser user = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, parentId).one();
        if (ObjectUtils.isEmpty(user)) {
            return;
        }
        String[] phone = {"+86" + user.getUserPhone()};
        request.setPhoneNumberSet(phone);
        request.setSignName("武汉本维美贸易");
        request.setTemplateId("2367629");
        request.setSmsSdkAppId("1400958886");
        tencentNoteTemPlate.sendTencentNote(request);
    }
}
